<template>
  <div class="data-table" :class="tableClass">
    <!-- 表格工具栏 -->
    <div v-if="showToolbar" class="data-table__toolbar">
      <!-- 左侧操作区 -->
      <div class="toolbar-left">
        <slot name="toolbar-left">
          <!-- 批量操作 -->
          <div v-if="selectedRows.length > 0" class="batch-actions">
            <span class="batch-info">
              已选择 <strong>{{ selectedRows.length }}</strong> 项
            </span>
            <slot name="batch-actions" :selected-rows="selectedRows">
              <el-button 
                size="small" 
                @click="clearSelection"
              >
                取消选择
              </el-button>
            </slot>
          </div>
        </slot>
      </div>
      
      <!-- 右侧操作区 -->
      <div class="toolbar-right">
        <slot name="toolbar-right">
          <el-button 
            v-if="refreshable" 
            size="small" 
            :icon="Refresh" 
            @click="handleRefresh"
            :loading="loading"
          >
            刷新
          </el-button>
          <el-button 
            v-if="exportable" 
            size="small" 
            :icon="Download" 
            @click="handleExport"
          >
            导出
          </el-button>
          <!-- 列设置 -->
          <el-popover 
            v-if="showColumnSetting" 
            placement="bottom-end" 
            :width="200"
            trigger="click"
          >
            <template #reference>
              <el-button size="small" :icon="Setting">列设置</el-button>
            </template>
            <div class="column-setting">
              <el-checkbox 
                v-for="col in configurableColumns" 
                :key="col.prop"
                v-model="col.visible"
                :label="col.label"
                class="column-checkbox"
              />
            </div>
          </el-popover>
        </slot>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      ref="tableRef"
      v-bind="tableProps"
      :data="tableData"
      :loading="loading"
      :height="tableHeight"
      :max-height="maxHeight"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      @filter-change="handleFilterChange"
      class="data-table__table"
    >
      <!-- 多选列 -->
      <el-table-column 
        v-if="selectable" 
        type="selection" 
        :width="selectionWidth"
        :fixed="selectionFixed"
      />
      
      <!-- 序号列 -->
      <el-table-column 
        v-if="showIndex" 
        type="index" 
        label="序号"
        :width="indexWidth"
        :fixed="indexFixed"
        :index="getIndex"
      />
      
      <!-- 动态列 -->
      <template v-for="column in visibleColumns" :key="column.prop">
        <el-table-column
          v-bind="getColumnProps(column)"
          :show-overflow-tooltip="column.showOverflowTooltip !== false"
        >
          <!-- 自定义头部 -->
          <template v-if="column.headerSlot" #header="scope">
            <slot :name="column.headerSlot" v-bind="scope" :column="column" />
          </template>
          
          <!-- 自定义内容 -->
          <template #default="scope">
            <!-- 插槽内容 -->
            <slot 
              v-if="column.slot" 
              :name="column.slot" 
              v-bind="scope" 
              :column="column"
            />
            <!-- 状态标签 -->
            <StatusTag 
              v-else-if="column.type === 'status'" 
              :status="scope.row[column.prop]"
              :status-map="column.statusMap"
              :size="column.tagSize"
            />
            <!-- 日期格式化 -->
            <span v-else-if="column.type === 'date'">
              {{ formatDate(scope.row[column.prop], column.dateFormat) }}
            </span>
            <!-- 数字格式化 -->
            <span v-else-if="column.type === 'number'">
              {{ formatNumber(scope.row[column.prop], column.numberFormat) }}
            </span>
            <!-- 链接 -->
            <el-link 
              v-else-if="column.type === 'link'"
              :type="column.linkType || 'primary'"
              @click="handleLinkClick(scope.row, column)"
            >
              {{ getCellValue(scope.row, column) }}
            </el-link>
            <!-- 标签 -->
            <el-tag 
              v-else-if="column.type === 'tag'"
              :type="column.tagType"
              :size="column.tagSize"
            >
              {{ getCellValue(scope.row, column) }}
            </el-tag>
            <!-- 默认文本 -->
            <span v-else>{{ getCellValue(scope.row, column) }}</span>
          </template>
        </el-table-column>
      </template>
      
      <!-- 操作列 -->
      <el-table-column 
        v-if="$slots.actions || actions.length > 0"
        label="操作"
        :width="actionWidth"
        :fixed="actionFixed"
        class-name="action-column"
      >
        <template #default="scope">
          <slot name="actions" v-bind="scope">
            <div class="table-actions">
              <template v-for="action in getRowActions(scope.row)" :key="action.key">
                <el-button
                  v-if="action.type === 'button'"
                  :type="action.buttonType"
                  :size="action.size || 'small'"
                  :icon="action.icon"
                  :disabled="action.disabled"
                  :loading="action.loading"
                  text
                  @click="handleActionClick(action, scope.row, scope.$index)"
                >
                  {{ action.text }}
                </el-button>
                
                <el-dropdown 
                  v-else-if="action.type === 'dropdown'"
                  @command="(command) => handleActionClick(command, scope.row, scope.$index)"
                >
                  <el-button :size="action.size || 'small'" text>
                    {{ action.text }}
                    <el-icon><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item 
                        v-for="item in action.items" 
                        :key="item.key"
                        :command="item"
                        :disabled="item.disabled"
                      >
                        <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
                        {{ item.text }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </div>
          </slot>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <div v-if="showEmpty" class="data-table__empty">
      <slot name="empty">
        <EmptyState
          :title="emptyTitle"
          :description="emptyDescription"
          :illustration="emptyIllustration"
          :show-default-action="emptyActionable"
          :action-text="emptyActionText"
          @action="handleEmptyAction"
        />
      </slot>
    </div>

    <!-- 分页 -->
    <div v-if="showPagination" class="data-table__pagination">
      <el-pagination
        v-bind="paginationProps"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { 
  Refresh, 
  Download, 
  Setting, 
  ArrowDown 
} from '@element-plus/icons-vue'
import { StatusTag, EmptyState } from '@/components'
import type { TableInstance } from 'element-plus'
import dayjs from 'dayjs'

export interface TableColumn {
  prop: string
  label: string
  width?: string | number
  minWidth?: string | number
  fixed?: boolean | 'left' | 'right'
  sortable?: boolean | 'custom'
  filterable?: boolean
  filters?: Array<{ text: string; value: any }>
  showOverflowTooltip?: boolean
  
  // 自定义类型
  type?: 'text' | 'status' | 'date' | 'number' | 'link' | 'tag' | 'slot'
  slot?: string
  headerSlot?: string
  
  // 状态标签相关
  statusMap?: Record<string | number, any>
  tagSize?: 'large' | 'default' | 'small'
  tagType?: string
  
  // 日期格式化
  dateFormat?: string
  
  // 数字格式化
  numberFormat?: {
    precision?: number
    separator?: string
    prefix?: string
    suffix?: string
  }
  
  // 链接相关
  linkType?: 'primary' | 'success' | 'warning' | 'danger' | 'info'
  linkAction?: string
  
  // 列显示控制
  visible?: boolean
  configurable?: boolean
}

export interface TableAction {
  key: string
  text: string
  type: 'button' | 'dropdown'
  buttonType?: 'primary' | 'success' | 'warning' | 'danger' | 'info'
  icon?: any
  size?: 'large' | 'default' | 'small'
  disabled?: boolean | ((row: any) => boolean)
  loading?: boolean | ((row: any) => boolean)
  visible?: boolean | ((row: any) => boolean)
  
  // 下拉菜单项
  items?: Array<{
    key: string
    text: string
    icon?: any
    disabled?: boolean | ((row: any) => boolean)
  }>
}

export interface DataTableProps {
  // 数据
  data?: any[]
  columns: TableColumn[]
  loading?: boolean
  
  // 分页
  showPagination?: boolean
  currentPage?: number
  pageSize?: number
  total?: number
  pageSizes?: number[]
  
  // 选择
  selectable?: boolean
  selectedRows?: any[]
  selectionWidth?: number
  selectionFixed?: boolean | 'left' | 'right'
  
  // 序号
  showIndex?: boolean
  indexWidth?: number
  indexFixed?: boolean | 'left' | 'right'
  
  // 操作
  actions?: TableAction[]
  actionWidth?: number
  actionFixed?: boolean | 'left' | 'right'
  
  // 工具栏
  showToolbar?: boolean
  refreshable?: boolean
  exportable?: boolean
  showColumnSetting?: boolean
  
  // 表格设置
  height?: string | number
  maxHeight?: string | number
  stripe?: boolean
  border?: boolean
  size?: 'large' | 'default' | 'small'
  
  // 空状态
  emptyTitle?: string
  emptyDescription?: string
  emptyIllustration?: string
  emptyActionable?: boolean
  emptyActionText?: string
}

const props = withDefaults(defineProps<DataTableProps>(), {
  data: () => [],
  loading: false,
  showPagination: true,
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: () => [10, 20, 50, 100],
  selectable: false,
  selectedRows: () => [],
  selectionWidth: 55,
  selectionFixed: 'left',
  showIndex: false,
  indexWidth: 60,
  indexFixed: 'left',
  actions: () => [],
  actionWidth: 150,
  actionFixed: 'right',
  showToolbar: true,
  refreshable: true,
  exportable: false,
  showColumnSetting: true,
  stripe: true,
  border: true,
  size: 'default',
  emptyTitle: '暂无数据',
  emptyDescription: '没有找到相关数据',
  emptyIllustration: 'no-data',
  emptyActionable: false,
  emptyActionText: '刷新'
})

const emit = defineEmits<{
  'selection-change': [selection: any[]]
  'sort-change': [sort: { column: any; prop: string; order: string }]
  'filter-change': [filters: any]
  'page-change': [page: number]
  'size-change': [size: number]
  'action-click': [action: string | TableAction, row: any, index: number]
  'link-click': [row: any, column: TableColumn]
  'refresh': []
  'export': []
  'empty-action': []
}>()

const tableRef = ref<TableInstance>()
const selectedRows = ref<any[]>([...props.selectedRows])

// 表格样式类
const tableClass = computed(() => [
  `data-table--${props.size}`,
  {
    'data-table--border': props.border,
    'data-table--stripe': props.stripe
  }
])

// 表格属性
const tableProps = computed(() => {
  const excluded = [
    'data', 'columns', 'loading', 'showPagination', 'currentPage', 'pageSize', 'total',
    'selectable', 'selectedRows', 'showIndex', 'actions', 'showToolbar', 'refreshable',
    'exportable', 'showColumnSetting', 'emptyTitle', 'emptyDescription', 'emptyIllustration'
  ]
  
  const result: Record<string, any> = {}
  Object.keys(props).forEach(key => {
    if (!excluded.includes(key)) {
      result[key] = (props as any)[key]
    }
  })
  
  return result
})

// 表格数据
const tableData = computed(() => props.data || [])

// 表格高度
const tableHeight = computed(() => {
  if (props.height) return props.height
  return undefined
})

// 可配置列
const configurableColumns = ref(
  props.columns
    .filter(col => col.configurable !== false)
    .map(col => ({
      ...col,
      visible: col.visible !== false
    }))
)

// 可见列
const visibleColumns = computed(() => 
  props.columns.filter(col => {
    if (col.configurable === false) return true
    const configCol = configurableColumns.value.find(c => c.prop === col.prop)
    return configCol?.visible !== false
  })
)

// 分页属性
const paginationProps = computed(() => ({
  background: true,
  layout: 'total, sizes, prev, pager, next, jumper',
  pageSizes: props.pageSizes,
  small: props.size === 'small'
}))

// 是否显示空状态
const showEmpty = computed(() => 
  !props.loading && tableData.value.length === 0
)

// 获取列属性
const getColumnProps = (column: TableColumn) => {
  const excluded = ['type', 'slot', 'headerSlot', 'statusMap', 'dateFormat', 'numberFormat', 'linkType', 'linkAction', 'visible', 'configurable', 'tagSize', 'tagType']
  const result: Record<string, any> = {}
  
  Object.keys(column).forEach(key => {
    if (!excluded.includes(key)) {
      result[key] = (column as any)[key]
    }
  })
  
  return result
}

// 获取单元格值
const getCellValue = (row: any, column: TableColumn) => {
  return row[column.prop] || ''
}

// 格式化日期
const formatDate = (date: any, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!date) return ''
  return dayjs(date).format(format)
}

// 格式化数字
const formatNumber = (num: any, format?: TableColumn['numberFormat']) => {
  if (num === null || num === undefined || num === '') return ''
  
  const number = Number(num)
  if (isNaN(number)) return num
  
  let result = format?.precision !== undefined 
    ? number.toFixed(format.precision)
    : number.toString()
  
  if (format?.separator) {
    result = result.replace(/\B(?=(\d{3})+(?!\d))/g, format.separator)
  }
  
  if (format?.prefix) result = format.prefix + result
  if (format?.suffix) result = result + format.suffix
  
  return result
}

// 获取索引
const getIndex = (index: number) => {
  return (props.currentPage - 1) * props.pageSize + index + 1
}

// 获取行操作
const getRowActions = (row: any) => {
  return props.actions.filter(action => {
    if (typeof action.visible === 'function') {
      return action.visible(row)
    }
    return action.visible !== false
  }).map(action => ({
    ...action,
    disabled: typeof action.disabled === 'function' ? action.disabled(row) : action.disabled,
    loading: typeof action.loading === 'function' ? action.loading(row) : action.loading
  }))
}

// 事件处理
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
  emit('selection-change', selection)
}

const handleSortChange = (sort: any) => {
  emit('sort-change', sort)
}

const handleFilterChange = (filters: any) => {
  emit('filter-change', filters)
}

const handleCurrentChange = (page: number) => {
  emit('page-change', page)
}

const handleSizeChange = (size: number) => {
  emit('size-change', size)
}

const handleActionClick = (action: string | TableAction, row: any, index: number) => {
  emit('action-click', action, row, index)
}

const handleLinkClick = (row: any, column: TableColumn) => {
  emit('link-click', row, column)
}

const handleRefresh = () => {
  emit('refresh')
}

const handleExport = () => {
  emit('export')
}

const handleEmptyAction = () => {
  emit('empty-action')
}

// 清除选择
const clearSelection = () => {
  tableRef.value?.clearSelection()
}

// 监听选中行变化
watch(() => props.selectedRows, (newSelection) => {
  selectedRows.value = [...newSelection]
}, { deep: true })

// 暴露方法
defineExpose({
  clearSelection,
  toggleRowSelection: (row: any, selected?: boolean) => {
    tableRef.value?.toggleRowSelection(row, selected)
  },
  toggleAllSelection: () => {
    tableRef.value?.toggleAllSelection()
  },
  clearSort: () => {
    tableRef.value?.clearSort()
  },
  clearFilter: (columnKey?: string) => {
    tableRef.value?.clearFilter(columnKey)
  },
  doLayout: () => {
    nextTick(() => {
      tableRef.value?.doLayout()
    })
  }
})
</script>

<style scoped>
/* 所有样式已迁移到模块化样式文件中：
 * - 数据表格样式 → src/styles/table-module.scss
 * - 工具栏样式 → src/styles/table-module.scss
 * - 响应式设计 → src/styles/table-module.scss
 *
 * 如有组件特定的样式需求，可在此添加
 */
</style>
